<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理员控制台 - 论坛系统</title>
    <link rel="stylesheet" href="/dist/css/tabler.min.css">
    <link rel="stylesheet" href="/dist/css/tabler-flags.min.css">
    <link rel="stylesheet" href="/dist/css/tabler-payments.min.css">
    <link rel="stylesheet" href="/dist/css/tabler-vendors.min.css">
    <!-- 注释掉不存在的CSS文件 -->
    <!-- <link rel="stylesheet" href="/dist/css/demo.min.css"> -->
    <!-- 修正jQuery库路径 -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
</head>
<body class="theme-light">
<div class="page">
    <!-- 顶部导航栏 -->
    <header class="navbar navbar-expand-md navbar-light d-print-none">
        <div class="container-xl">
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbar-menu">
                <span class="navbar-toggler-icon"></span>
            </button>
            <h1 class="navbar-brand navbar-brand-autodark d-none-navbar-horizontal pe-0 pe-md-3">
                <a href="/">论坛系统 - 管理员控制台</a>
            </h1>
            <div class="navbar-nav flex-row order-md-last">
                <div class="nav-item dropdown">
                    <a href="#" class="nav-link d-flex lh-1 text-reset p-0" data-bs-toggle="dropdown" aria-label="打开用户菜单">
                        <span class="avatar avatar-sm" id="admin-avatar">管理</span>
                        <div class="d-none d-xl-block ps-2">
                            <div id="admin-name">管理员</div>
                        </div>
                    </a>
                    <div class="dropdown-menu dropdown-menu-end dropdown-menu-arrow">
                        <a href="/" class="dropdown-item">返回首页</a>
                        <a href="#" class="dropdown-item" id="logout-btn">退出登录</a>
                    </div>
                </div>
            </div>
        </div>
    </header>

    <!-- 侧边导航菜单 -->
    <div class="navbar-expand-md">
        <div class="collapse navbar-collapse" id="navbar-menu">
            <div class="navbar navbar-light">
                <div class="container-xl">
                    <ul class="navbar-nav">
                        <li class="nav-item active">
                            <a class="nav-link" href="#dashboard" data-section="dashboard">
                                <span class="nav-link-icon d-md-none d-lg-inline-block">
                                    <svg xmlns="http://www.w3.org/2000/svg" class="icon" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><polyline points="5 12 3 12 12 3 21 12 19 12" /><path d="M5 12v7a2 2 0 0 0 2 2h10a2 2 0 0 0 2 -2v-7" /><path d="M9 21v-6a2 2 0 0 1 2 -2h2a2 2 0 0 1 2 2v6" /></svg>
                                </span>
                                <span class="nav-link-title">统计概览</span>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#users" data-section="users">
                                <span class="nav-link-icon d-md-none d-lg-inline-block">
                                    <svg xmlns="http://www.w3.org/2000/svg" class="icon" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><circle cx="9" cy="7" r="4" /><path d="M3 21v-2a4 4 0 0 1 4 -4h4a4 4 0 0 1 4 4v2" /><path d="M16 3.13a4 4 0 0 1 0 7.75" /><path d="M21 21v-2a4 4 0 0 0 -3 -3.85" /></svg>
                                </span>
                                <span class="nav-link-title">用户管理</span>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#boards" data-section="boards">
                                <span class="nav-link-icon d-md-none d-lg-inline-block">
                                    <svg xmlns="http://www.w3.org/2000/svg" class="icon" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><rect x="4" y="4" width="16" height="16" rx="2" /><line x1="4" y1="10" x2="20" y2="10" /><line x1="10" y1="4" x2="10" y2="20" /></svg>
                                </span>
                                <span class="nav-link-title">板块管理</span>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#articles" data-section="articles">
                                <span class="nav-link-icon d-md-none d-lg-inline-block">
                                    <svg xmlns="http://www.w3.org/2000/svg" class="icon" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M14 3v4a1 1 0 0 0 1 1h4" /><path d="M17 21h-10a2 2 0 0 1 -2 -2v-14a2 2 0 0 1 2 -2h7l5 5v11a2 2 0 0 1 -2 2z" /><line x1="9" y1="9" x2="10" y2="9" /><line x1="9" y1="13" x2="15" y2="13" /><line x1="9" y1="17" x2="15" y2="17" /></svg>
                                </span>
                                <span class="nav-link-title">文章管理</span>
                            </a>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    </div>

    <!-- 主内容区 -->
    <div class="page-wrapper">
        <div class="container-xl">
            <div class="page-header d-print-none">
                <div class="row align-items-center">
                    <div class="col">
                        <h2 class="page-title" id="page-title">系统概览</h2>
                    </div>
                    <div class="col-auto ms-auto">
                        <button class="btn btn-primary" id="refresh-stats-btn">
                            <svg xmlns="http://www.w3.org/2000/svg" class="icon" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M20 11a8.1 8.1 0 0 0 -15.5 -2m-.5 -4v4h4" /><path d="M4 13a8.1 8.1 0 0 0 15.5 2m.5 4v-4h-4" /></svg>
                            刷新统计数据
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <div class="page-body">
            <div class="container-xl">
                <!-- 统计概览部分 -->
                <div class="section-content" id="dashboard-section">
                    <div class="row">
                        <div class="col-md-6 col-lg-4">
                            <div class="card">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="subheader">用户总数</div>
                                    </div>
                                    <div class="h1 mb-3" id="total-users">0</div>
                                    <div class="d-flex mb-2">
                                        <div>今日新增</div>
                                        <div class="ms-auto"><span class="text-green" id="today-users">0</span></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6 col-lg-4">
                            <div class="card">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="subheader">文章总数</div>
                                    </div>
                                    <div class="h1 mb-3" id="total-articles">0</div>
                                    <div class="d-flex mb-2">
                                        <div>今日新增</div>
                                        <div class="ms-auto"><span class="text-green" id="today-articles">0</span></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6 col-lg-4">
                            <div class="card">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="subheader">访问量</div>
                                    </div>
                                    <div class="h1 mb-3" id="total-visits">0</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 用户管理部分 -->
                <div class="section-content d-none" id="users-section">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">用户列表</h3>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-vcenter">
                                    <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>用户名</th>
                                        <th>昵称</th>
                                        <th>邮箱</th>
                                        <th>文章数</th>
                                        <th>状态</th>
                                        <th>管理员</th>
                                        <th>操作</th>
                                    </tr>
                                    </thead>
                                    <tbody id="users-table-body">
                                    <!-- 用户列表将通过JavaScript动态加载 -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 板块管理部分 -->
                <div class="section-content d-none" id="boards-section">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">板块列表</h3>
                            <div class="card-actions">
                                <button class="btn btn-primary me-2" id="fix-board-counts-btn">修复文章计数</button>
                                <button class="btn btn-primary" id="add-board-btn">添加板块</button>
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-vcenter">
                                    <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>板块名称</th>
                                        <th>文章数</th>
                                        <th>排序</th>
                                        <th>状态</th>
                                        <th>操作</th>
                                    </tr>
                                    </thead>
                                    <tbody id="boards-table-body">
                                    <!-- 板块列表将通过JavaScript动态加载 -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 文章管理部分 -->
                <div class="section-content d-none" id="articles-section">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">文章列表</h3>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-vcenter">
                                    <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>标题</th>
                                        <th>作者</th>
                                        <th>所属板块</th>
                                        <th>发布时间</th>
                                        <th>状态</th>
                                        <th>操作</th>
                                    </tr>
                                    </thead>
                                    <tbody id="articles-table-body">
                                        <!-- 文章列表将通过JavaScript动态加载 -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 页脚 -->
        <footer class="footer footer-transparent d-print-none">
            <div class="container-xl">
                <div class="row text-center align-items-center flex-row-reverse">
                    <div class="col-12 col-lg-auto mt-3 mt-lg-0">
                        <ul class="list-inline list-inline-dots mb-0">
                            <li class="list-inline-item">
                                Copyright &copy; 2023 论坛系统
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
        </footer>
    </div>
</div>

<!-- 用户状态变更模态框 -->
<div class="modal modal-blur fade" id="user-state-modal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">修改用户状态</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>您确定要修改该用户的状态吗？</p>
                <input type="hidden" id="user-id-state">
                <input type="hidden" id="user-state-value">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-link link-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="confirm-state-btn">确认修改</button>
            </div>
        </div>
    </div>
</div>

<!-- 用户管理员权限变更模态框 -->
<div class="modal modal-blur fade" id="user-admin-modal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">修改管理员权限</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>您确定要修改该用户的管理员权限吗？</p>
                <input type="hidden" id="user-id-admin">
                <input type="hidden" id="user-admin-value">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-link link-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="confirm-admin-btn">确认修改</button>
            </div>
        </div>
    </div>
</div>

<!-- 添加文章管理模态框 -->
<div class="modal fade" id="article-modal" tabindex="-1" aria-labelledby="articleModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="articleModalLabel">操作确认</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <p id="article-modal-message">确定要执行此操作吗？</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
        <button type="button" class="btn btn-primary" id="article-modal-confirm">确定</button>
      </div>
    </div>
  </div>
</div>

<!-- 添加板块模态框 -->
<div class="modal modal-blur fade" id="board-add-modal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">添加板块</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label required">板块名称</label>
                    <input type="text" class="form-control" id="board-add-name" placeholder="请输入板块名称" required>
                </div>
                <div class="mb-3">
                    <label class="form-label">排序值</label>
                    <input type="number" class="form-control" id="board-add-sort" placeholder="数值越小排序越靠前" value="0">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-link link-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="board-add-submit">添加</button>
            </div>
        </div>
    </div>
</div>

<!-- 编辑板块模态框 -->
<div class="modal modal-blur fade" id="board-edit-modal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">编辑板块</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="board-edit-id">
                <div class="mb-3">
                    <label class="form-label required">板块名称</label>
                    <input type="text" class="form-control" id="board-edit-name" placeholder="请输入板块名称" required>
                </div>
                <div class="mb-3">
                    <label class="form-label">排序值</label>
                    <input type="number" class="form-control" id="board-edit-sort" placeholder="数值越小排序越靠前">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-link link-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="board-edit-submit">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 删除板块确认模态框 -->
<div class="modal modal-blur fade" id="board-delete-modal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">删除板块</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>您确定要删除这个板块吗？这将会删除该板块下的所有帖子！</p>
                <input type="hidden" id="board-delete-id">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-link link-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="board-delete-submit">确认删除</button>
            </div>
        </div>
    </div>
</div>

<!-- 板块状态确认模态框 -->
<div class="modal modal-blur fade" id="board-state-modal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">修改板块状态</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>您确定要修改该板块的状态吗？</p>
                <input type="hidden" id="board-state-id">
                <input type="hidden" id="board-state-value">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-link link-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="board-state-submit">确认修改</button>
            </div>
        </div>
    </div>
</div>

<!-- JS脚本引入 -->
<script src="/dist/js/tabler.min.js" defer></script>
<!-- 注释掉不存在的JS文件 -->
<!-- <script src="/dist/js/demo.min.js" defer></script> -->
<script>
    $(document).ready(function() {
        // 初始化侧边导航菜单事件
        initSidebarMenu();
        
        // 加载控制台概览数据
        loadDashboardData();
        
        // 加载用户列表（默认加载）
        loadUsersList();
        
        // 绑定用户事件
        bindUserActions();
        
        // 绑定板块事件
        bindBoardActions();
        
        // 绑定文章事件
        bindArticleActions();
    });
    
    // 初始化侧边栏菜单
    function initSidebarMenu() {
        // 定义各部分对应的内容区域ID
        const sections = {
            'dashboard': 'dashboard-section',
            'users': 'users-section',
            'boards': 'boards-section',
            'articles': 'articles-section'
        };
        
        // 点击导航菜单项时的处理
        $('.navbar-nav .nav-link').click(function(e) {
            e.preventDefault();
            
            // 获取对应的部分
            const section = $(this).attr('data-section');
            
            // 更新页面标题
            let sectionTitle = $(this).find('.nav-link-title').text();
            $('#page-title').text(sectionTitle);
            
            // 更新菜单激活状态
            $('.navbar-nav .nav-item').removeClass('active');
            $(this).parent().addClass('active');
            
            // 隐藏所有内容区域
            $('.section-content').addClass('d-none');
            
            // 显示对应的内容区域
            const targetSection = sections[section];
            $('#' + targetSection).removeClass('d-none');
            
            // 根据目标加载不同数据
            if (section === 'dashboard') {
                loadDashboardData();
            } else if (section === 'users') {
                loadUsersList();
            } else if (section === 'boards') {
                loadBoardsList();
            } else if (section === 'articles') {
                loadArticleList();
            }
        });
        
        // 刷新统计按钮点击事件
        $('#refresh-stats-btn').click(function() {
            loadDashboardData();
        });
    }
    
    // 加载控制台概览数据
    function loadDashboardData() {
        $.ajax({
            url: '/admin/stats',
            type: 'GET',
            success: function(res) {
                if (res.code === 0) {
                    console.log("统计数据:", res.data);
                    const stats = res.data;
                    // 更新用户数据
                    $('#total-users').text(stats.totalUsers || 0);
                    $('#today-users').text(stats.todayNewUsers || 0);
                    
                    // 更新文章数据
                    $('#total-articles').text(stats.totalArticles || 0);
                    $('#today-articles').text(stats.todayNewArticles || 0);
                    
                    // 更新访问量数据
                    $('#total-visits').text(stats.totalVisits || 0);
                } else {
                    console.error('加载统计数据失败:', res.message);
                }
            },
            error: function(err) {
                console.error('加载统计数据出错:', err);
            }
        });
    }
    
    // 加载板块列表
    function loadBoardsList() {
        $.ajax({
            url: '/admin/board/list',
            type: 'GET',
            success: function(res) {
                if (res.code === 0) {
                    renderBoardsList(res.data);
                } else {
                    console.error('加载板块列表失败:', res.message);
                    $('#boards-table-body').html('<tr><td colspan="6" class="text-center text-danger">加载失败: ' + res.message + '</td></tr>');
                }
            },
            error: function(err) {
                console.error('加载板块列表出错:', err);
                $('#boards-table-body').html('<tr><td colspan="6" class="text-center text-danger">网络错误，请重试</td></tr>');
            }
        });
    }

    // 初始检查完成后将调用此方法
    function onAdminAuthSuccess() {
        // 加载用户信息
        loadUserInfo();
        // 初始化管理员功能
        initAdminFunctions();
    }
    
    // 初始化管理员功能
    function initAdminFunctions() {
        // 导航切换
        $('a[data-section]').on('click', function(e) {
            e.preventDefault();
            const section = $(this).data('section');
            
            // 更新导航激活状态
            $('a[data-section]').parent().removeClass('active');
            $(this).parent().addClass('active');
            
            // 更新标题
            let title = '';
            switch(section) {
                case 'dashboard': title = '系统概览'; break;
                case 'users': title = '用户管理'; break;
                case 'boards': title = '板块管理'; break;
                case 'articles': title = '文章管理'; break;
            }
            $('#page-title').text(title);
            
            // 显示对应的内容区域
            $('.section-content').addClass('d-none');
            $(`#${section}-section`).removeClass('d-none');
            
            // 加载内容
            if (section === 'dashboard') {
                loadDashboardData();
            } else if (section === 'users') {
                loadUsersList();
            } else if (section === 'boards') {
                loadBoardsList();
            } else if (section === 'articles') {
                loadArticleList();
            }
        });
        
        // 初始显示仪表盘
        loadDashboardData();
        
        // 退出登录
        $('#logout-btn').on('click', function() {
            if (confirm('确定要退出登录吗？')) {
                logout();
            }
        });
        
        // 添加板块按钮
        $('#add-board-btn').on('click', function() {
            $('#board-add-name').val('');
            $('#board-add-sort').val('0');
            $('#board-add-modal').modal('show');
        });
        
        // 添加板块表单提交
        $('#board-add-submit').on('click', function() {
            const name = $('#board-add-name').val().trim();
            const sort = $('#board-add-sort').val().trim();
            
            if (!name) {
                alert('请输入板块名称');
                return;
            }
            
            $.ajax({
                url: '/admin/board/add',
                type: 'POST',
                data: {
                    name: name,
                    sort: sort || 0
                },
                success: function(res) {
                    if (res.code === 0) {
                        $('#board-add-modal').modal('hide');
                        loadBoardsList(); // 重新加载板块列表
                        // 更新统计信息
                        loadDashboardData();
                    } else {
                        alert(res.message || '添加失败');
                    }
                },
                error: function() {
                    alert('网络错误，请重试');
                }
            });
        });
        
        // 编辑板块表单提交
        $('#board-edit-submit').on('click', function() {
            const id = $('#board-edit-id').val();
            const name = $('#board-edit-name').val().trim();
            const sort = $('#board-edit-sort').val().trim();
            
            if (!name) {
                alert('请输入板块名称');
                return;
            }
            
            $.ajax({
                url: '/admin/board/update',
                type: 'POST',
                data: {
                    boardId: id,
                    name: name,
                    sort: sort || 0
                },
                success: function(res) {
                    if (res.code === 0) {
                        $('#board-edit-modal').modal('hide');
                        loadBoardsList(); // 重新加载板块列表
                    } else {
                        alert(res.message || '更新失败');
                    }
                },
                error: function() {
                    alert('网络错误，请重试');
                }
            });
        });
        
        // 用户状态确认按钮
        $('#confirm-state-btn').on('click', function() {
            // 再次验证管理员权限
            recheckAdminAuth(function() {
                const userId = $('#user-id-state').val();
                const state = $('#user-state-value').val();
                
                $.ajax({
                    url: '/admin/user/state',
                    type: 'POST',
                    data: {
                        userId: userId,
                        state: state
                    },
                    success: function(res) {
                        if (res.code === 0) {
                            $('#user-state-modal').modal('hide');
                            loadUsersList(); // 重新加载用户列表
                        } else {
                            alert(res.message || '操作失败');
                            if (res.code === 401 || res.code === 403) {
                                window.location.href = '/unauthorized.html';
                            }
                        }
                    },
                    error: function(xhr) {
                        if (xhr.status === 401 || xhr.status === 403) {
                            window.location.href = '/unauthorized.html';
                        } else {
                            alert('网络错误，请重试');
                        }
                    }
                });
            });
        });
        
        // 管理员权限确认按钮
        $('#confirm-admin-btn').on('click', function() {
            // 再次验证管理员权限
            recheckAdminAuth(function() {
                const userId = $('#user-id-admin').val();
                const isAdmin = $('#user-admin-value').val();
                
                $.ajax({
                    url: '/admin/user/admin',
                    type: 'POST',
                    data: {
                        userId: userId,
                        isAdmin: isAdmin
                    },
                    success: function(res) {
                        if (res.code === 0) {
                            $('#user-admin-modal').modal('hide');
                            loadUsersList(); // 重新加载用户列表
                        } else {
                            alert(res.message || '操作失败');
                            if (res.code === 401 || res.code === 403) {
                                window.location.href = '/unauthorized.html';
                            }
                        }
                    },
                    error: function(xhr) {
                        if (xhr.status === 401 || xhr.status === 403) {
                            window.location.href = '/unauthorized.html';
                        } else {
                            alert('网络错误，请重试');
                        }
                    }
                });
            });
        });
        
        // 添加刷新按钮的点击事件
        $('#refresh-stats-btn').on('click', function() {
            // 再次验证管理员权限
            recheckAdminAuth(function() {
                console.log("手动刷新统计数据");
                // 使用管理员接口加载数据
                fetch('/admin/stats')
                    .then(response => {
                        console.log("Response status:", response.status);
                        if (response.status === 401 || response.status === 403) {
                            window.location.href = '/unauthorized.html';
                            return Promise.reject('未授权');
                        }
                        return response.json();
                    })
                    .then(data => {
                        console.log("API返回数据:", data);
                        if (data.code === 0) {
                            const stats = data.data;
                            $('#total-users').text(stats.totalUsers);
                            $('#total-articles').text(stats.totalArticles);
                            $('#total-visits').text(stats.totalVisits);
                            $('#today-users').text(stats.todayNewUsers);
                            $('#today-articles').text(stats.todayNewArticles);
                            alert("统计数据已刷新!");
                        } else {
                            alert("加载失败: " + data.message);
                            if (data.code === 401 || data.code === 403) {
                                window.location.href = '/unauthorized.html';
                            }
                        }
                    })
                    .catch(error => {
                        console.error("fetch错误:", error);
                        if (error !== '未授权') {
                            alert("加载失败，请查看控制台");
                        }
                    });
            });
        });
    }

    // 检查管理员权限
    function checkAdminAuth() {
        $.ajax({
            url: '/admin/check',
            type: 'GET',
            success: function(res) {
                if (res.code !== 0) {
                    // 非管理员，跳转到未授权页面
                    window.location.href = '/unauthorized.html';
                } else {
                    // 初始化管理员功能
                    onAdminAuthSuccess();
                }
            },
            error: function() {
                window.location.href = '/unauthorized.html';
            }
        });
    }

    // 加载用户信息
    function loadUserInfo() {
        $.ajax({
            url: '/user/info',
            type: 'GET',
            success: function(res) {
                if (res.code === 0) {
                    const user = res.data;
                    $('#admin-name').text(user.nickname);
                    if (user.avatarUrl) {
                        $('#admin-avatar').html(`<img src="${user.avatarUrl}" alt="管理员头像">`);
                    } else {
                        $('#admin-avatar').text(user.nickname.charAt(0));
                    }
                }
            }
        });
    }

    // 再次检查管理员权限
    function recheckAdminAuth(callback) {
        $.ajax({
            url: '/admin/check',
            type: 'GET',
            success: function(res) {
                if (res.code !== 0) {
                    // 非管理员，跳转到未授权页面
                    window.location.href = '/unauthorized.html';
                } else {
                    // 已验证权限，执行回调
                    callback();
                }
            },
            error: function() {
                window.location.href = '/unauthorized.html';
            }
        });
    }
    
    // 加载用户列表
    function loadUsersList() {
        $.ajax({
            url: '/admin/users',
            type: 'GET',
            success: function(res) {
                if (res.code === 0) {
                    const users = res.data;
                    let html = '';
                    
                    users.forEach(user => {
                        const stateText = user.state === 0 ? '正常' : '禁言';
                        const stateBtn = user.state === 0 
                            ? `<button class="btn btn-sm btn-danger" onclick="changeUserState(${user.id}, 1)">禁言</button>`
                            : `<button class="btn btn-sm btn-success" onclick="changeUserState(${user.id}, 0)">解禁</button>`;
                            
                        const adminText = user.isAdmin === 1 ? '是' : '否';
                        const adminBtn = user.isAdmin === 0
                            ? `<button class="btn btn-sm btn-primary" onclick="changeUserAdmin(${user.id}, 1)">设为管理员</button>`
                            : `<button class="btn btn-sm btn-secondary" onclick="changeUserAdmin(${user.id}, 0)">取消管理员</button>`;
                            
                        html += `
                            <tr>
                                <td>${user.id}</td>
                                <td>${user.username}</td>
                                <td>${user.nickname}</td>
                                <td>${user.email || '-'}</td>
                                <td>${user.articleCount}</td>
                                <td>${stateText}</td>
                                <td>${adminText}</td>
                                <td>
                                    ${stateBtn}
                                    ${adminBtn}
                                </td>
                            </tr>
                        `;
                    });
                    
                    $('#users-table-body').html(html);
                }
            }
        });
    }

    // 修改用户状态
    function changeUserState(userId, state) {
        $('#user-id-state').val(userId);
        $('#user-state-value').val(state);
        $('#user-state-modal').modal('show');
    }

    // 修改用户管理员权限
    function changeUserAdmin(userId, isAdmin) {
        $('#user-id-admin').val(userId);
        $('#user-admin-value').val(isAdmin);
        $('#user-admin-modal').modal('show');
    }

    // 加载文章列表
    function loadArticleList() {
      console.log("加载文章列表");
      
      // 更新当前选中菜单
      $(".sidebar .nav-item .active").removeClass("active");
      $(".sidebar a[data-section='articles']").parent().addClass("active");
      
      // 更新页面标题
      $("#page-title").text("文章管理");
      
      // 隐藏其他内容区域，显示文章区域
      $(".section-content").addClass("d-none");
      $("#articles-section").removeClass("d-none");
      
      // 清空文章表格主体
      $("#articles-table-body").empty();
      
      // AJAX请求获取文章列表
      $.ajax({
        url: "/admin/article/list",
        type: "GET",
        success: function(res) {
          console.log("文章列表数据:", res);
          if (res.code === 0) {
            // 直接在表格中渲染数据
            renderArticleTable(res.data);
          } else {
            alert("获取文章列表失败：" + res.message);
          }
        },
        error: function() {
          alert("获取文章列表请求失败，请检查网络连接");
        }
      });
    }

    // 直接在表格中渲染文章数据
    function renderArticleTable(articles) {
      console.log("渲染文章表格，数据条数:", articles ? articles.length : 0);
      
      // 获取表格主体元素
      var tableBody = $("#articles-table-body");
      
      // 清空现有内容
      tableBody.empty();
      
      // 检查是否有数据
      if (!articles || articles.length === 0) {
        tableBody.html('<tr><td colspan="7" class="text-center">暂无文章数据</td></tr>');
        return;
      }
      
      // 渲染每一行
      for (var i = 0; i < articles.length; i++) {
        var article = articles[i];
        var statusBadge = article.state === 0 
          ? '<span class="badge bg-success">正常</span>' 
          : '<span class="badge bg-danger">禁用</span>';
        
        var row = $("<tr></tr>");
        row.append($("<td></td>").text(article.id));
        row.append($("<td></td>").text(article.title));
        row.append($("<td></td>").text(article.userName || "未知用户"));
        row.append($("<td></td>").text(article.boardName || "未知板块"));
        row.append($("<td></td>").text(new Date(article.createTime).toLocaleString()));
        row.append($("<td></td>").html(statusBadge));
        
        var actionButtons = '';
        if (article.state === 0) {
          actionButtons += `<button class="btn btn-warning btn-sm m-1" onclick="changeArticleState(${article.id}, 1)">禁用</button>`;
        } else {
          actionButtons += `<button class="btn btn-success btn-sm m-1" onclick="changeArticleState(${article.id}, 0)">启用</button>`;
        }
        actionButtons += `<button class="btn btn-danger btn-sm m-1" onclick="confirmDeleteArticle(${article.id})">删除</button>`;
        
        row.append($("<td></td>").html(actionButtons));
        tableBody.append(row);
      }
    }

    // 更改文章状态
    function changeArticleState(articleId, state) {
      var actionText = state === 0 ? "启用" : "禁用";
      
      // 设置模态框内容
      $("#article-modal-message").text(`确定要${actionText}该文章吗？`);
      $("#article-modal-confirm").off("click").on("click", function() {
        $.ajax({
          url: "/admin/article/status",
          type: "POST",
          data: {
            articleId: articleId,
            state: state
          },
          success: function(res) {
            var modal = bootstrap.Modal.getInstance(document.getElementById('article-modal'));
            modal.hide();
            if (res.code === 0) {
              alert(`文章${actionText}成功`);
              // 重新加载文章列表
              loadArticleList();
            } else {
              alert(`文章${actionText}失败：` + res.message);
            }
          },
          error: function() {
            var modal = bootstrap.Modal.getInstance(document.getElementById('article-modal'));
            modal.hide();
            alert("请求失败，请检查网络连接");
          }
        });
      });
      
      // 显示模态框
      var modal = new bootstrap.Modal(document.getElementById('article-modal'));
      modal.show();
    }

    // 确认删除文章
    function confirmDeleteArticle(articleId) {
      // 设置模态框内容
      $("#article-modal-message").text("确定要删除该文章吗？此操作不可撤销！");
      $("#article-modal-confirm").off("click").on("click", function() {
        $.ajax({
          url: "/admin/article/delete",
          type: "POST",
          data: {
            articleId: articleId
          },
          success: function(res) {
            var modal = bootstrap.Modal.getInstance(document.getElementById('article-modal'));
            modal.hide();
            if (res.code === 0) {
              alert("文章删除成功");
              // 重新加载文章列表
              loadArticleList();
            } else {
              alert("文章删除失败：" + res.message);
            }
          },
          error: function() {
            var modal = bootstrap.Modal.getInstance(document.getElementById('article-modal'));
            modal.hide();
            alert("请求失败，请检查网络连接");
          }
        });
      });
      
      // 显示模态框
      var modal = new bootstrap.Modal(document.getElementById('article-modal'));
      modal.show();
    }

    // =============== 板块管理功能 ===============
    // 渲染板块列表
    function renderBoardsList(boards) {
        if (!boards || boards.length === 0) {
            $('#boards-table-body').html('<tr><td colspan="6" class="text-center">暂无板块数据</td></tr>');
            return;
        }
        
        let html = '';
        boards.forEach(board => {
            html += `
            <tr>
                <td>${board.id}</td>
                <td>${board.name}</td>
                <td>${board.articleCount || 0}</td>
                <td>${board.sort || 0}</td>
                <td>${board.state === 0 ? '<span class="badge bg-success">正常</span>' : '<span class="badge bg-danger">禁用</span>'}</td>
                <td>
                    <div class="btn-list">
                        <button class="btn btn-sm btn-outline-primary fix-board-count" data-id="${board.id}">修复计数</button>
                        <button class="btn btn-sm btn-outline-primary edit-board" data-board='${JSON.stringify(board)}'>编辑</button>
                        <button class="btn btn-sm btn-outline-danger delete-board" data-id="${board.id}">删除</button>
                    </div>
                </td>
            </tr>
            `;
        });
        
        $('#boards-table-body').html(html);
        
        // 绑定修复计数按钮事件
        $('.fix-board-count').on('click', function() {
            const boardId = $(this).data('id');
            if (!confirm(`确定要修复ID为 ${boardId} 的板块文章计数吗？`)) {
                return;
            }
            
            // 显示加载中
            const $btn = $(this);
            const originalText = $btn.text();
            $btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>');
            
            $.ajax({
                url: '/admin/board/fixArticleCount',
                type: 'POST',
                data: {id: boardId},
                success: function(res) {
                    if (res.code === 0) {
                        const result = res.data;
                        if (result.fixed) {
                            alert(`修复成功: ${result.boardName} 的文章计数从 ${result.oldCount} 修改为 ${result.newCount}`);
                        } else {
                            alert(`板块 ${result.boardName} 的文章计数已是正确值: ${result.newCount}`);
                        }
                        // 重新加载板块列表
                        loadBoardsList();
                    } else {
                        // 显示错误消息
                        alert(`修复失败: ${res.message}`);
                    }
                },
                error: function(err) {
                    console.error('修复板块文章计数出错:', err);
                    alert('网络错误，请重试');
                },
                complete: function() {
                    // 恢复按钮状态
                    $btn.prop('disabled', false).text(originalText);
                }
            });
        });
        
        // 绑定编辑按钮事件
        $('.edit-board').on('click', function() {
            const board = $(this).data('board');
            // 填充编辑模态框
            $('#board-edit-id').val(board.id);
            $('#board-edit-name').val(board.name);
            $('#board-edit-sort').val(board.sort || 0);
            
            // 显示编辑模态框
            $('#board-edit-modal').modal('show');
        });
        
        // 绑定删除按钮事件
        $('.delete-board').on('click', function() {
            const boardId = $(this).data('id');
            // 填充删除模态框ID
            $('#board-delete-id').val(boardId);
            
            // 显示删除确认模态框
            $('#board-delete-modal').modal('show');
        });
    }
</script>
</body>
</html> 